from django.contrib.auth.models import User, AbstractUser
# TODO: 2.一对一外键
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.db import models


# TODO 1.设置Proxy模型
# 如果模型是一个代理模型
# 那么就不能再这个模型中添加新的Field

# User.objects.all()
# 等价于
# cls.objects.all()
class Person(User):
    # telphone = models.CharField(max_length=11)

    class Meta:
        proxy = True

    @classmethod
    def get_blacklist(cls):
        """返回不可用账户"""
        return cls.objects.filter(is_active=0)


# TODO 2.一对一外键
class UserExtension(models.Model):
    # TODO: 与User进行一对一绑定
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='extension')
    telphone = models.CharField(max_length=11)
    school = models.CharField(max_length=100)


# TODO 2.一对一外键
# 注册信号，监听save操作
@receiver(post_save, sender=User)
def my_user_extension(sender, instance, created, **kwargs):
    if created:   # TODO: 新创建数据
        UserExtension.objects.create(user=instance)
    else:   # TODO: 更新数据
        instance.extension.save()

